<template>
  <div>
    <!-- 查询条件表单 -->
    <el-form :inline="true" class="mb-4">
      <!-- 编码 Filter -->
      <el-form-item label="编码">
        <el-input v-model="queryConditions.code" style="width: 200px" size="large" placeholder="请输入编码" clearable />
      </el-form-item>

      <!-- 状态 Filter -->
      <el-form-item label="状态">
        <el-select v-model="queryConditions.status" placeholder="请选择状态" style="width: 160px" size="large" clearable>
          <el-option label="全部" :value="null" />
          <el-option label="待审核" :value="1" />
          <el-option label="已审核" :value="2" />
          <el-option label="已驳回" :value="3" />
        </el-select>
      </el-form-item>

      <el-form-item label="单据日期：">
          <el-date-picker
            v-model="queryConditions.dateRange"
            type="daterange"
            range-separator="至"
            :start-placeholder="queryConditions.dateRange[0] || '请选择开始'"
            :end-placeholder="queryConditions.dateRange[1] || 'A'"
          />
        </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" @click="fetchData(1)">查询</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <input
        type="file"
        ref="fileInput"
        style="display: none"
        accept=".xlsx,.xls"
        @change="handleFileSelect"
    />

    <!-- 列表组件 -->
    <TestPage :table-data="tableData" :columns="tableColumns" :current-page="pageNo" :total="total"
      :page-size="pageSize" @page-change="handlePageChange" @action="handleTableAction" @edit="openEditDialog"
      @delete="handleDelete" @row-audit="handleRowAudit"/>

    <!-- 编辑对话框（如果需要内嵌对话框，可解注释） -->
    <!--
    <CostAdjustmentEditDialog
      v-model:visible="editVisible"
      :row="editRow"
      @saved="onSaved"
    />
    -->

    <!-- 审核对话框 -->
    <el-dialog
        v-model="auditDialogVisible"
        title="单据审核"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form :model="auditForm" :rules="auditRules" ref="auditFormRef">
        <el-form-item label="单据编号：" prop="code">
          <el-input
              v-model="auditForm.code"
              disabled
              placeholder="系统自动填充"
          />
        </el-form-item>

        <el-form-item label="审核人：" prop="auditor">
          <el-select
              v-model="auditForm.auditor"
              placeholder="请选择审核人"
              filterable
              clearable
              style="width: 100%"
          >
            <el-option
                v-for="user in userList"
                :key="user.id"
                :label="`${user.name} `"
                :value="user.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="审批意见：" prop="comment">
          <el-input
              v-model="auditForm.comment"
              type="textarea"
              :rows="3"
              placeholder="请输入审批意见"
              maxlength="200"
              show-word-limit
          />
        </el-form-item>
        <el-form-item label="审核结果：" prop="checkResult">
          <el-select
              v-model="auditForm.checkRes"
              placeholder="请选择审核结果"
              style="width: 100%"
          >
            <el-option label="通过" :value="true" />
            <el-option label="不通过" :value="false" />
          </el-select>
        </el-form-item>

      </el-form>

      <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">提交审核</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import request from '@/util/request'
import { ElMessageBox, ElMessage } from 'element-plus'
import TestPage from '@/test/TestPage.vue'
import { useRouter } from 'vue-router'
import type { CostAdjustment } from '@/types/kc/CBTZ'
import type {User} from "@/types/rs/User.ts";
// 分页与查询状态
const pageNo = ref(1)
const pageSize = ref(5)
const total = ref(0)
const auditDialogVisible = ref(false);
interface QueryConditions {
  code: string
  status: number | null
  dateRange: [string, string] | []
}
const queryConditions = reactive<QueryConditions>({
  code: '',
  status: null,
  dateRange: []
})

let userList=ref<User[]>([])
let selectUser=async()=>{
  let response=await request.post('per/user/getAll')
  userList.value=response.data.data
  console.log(userList.value)
}
selectUser()

const userInfo = sessionStorage.getItem('user');
const user = userInfo ? JSON.parse(userInfo) : null;

const auditors = ref([
    { id: user.user.id, name:user.user.name, dept: '仓管部门' }
]);

// 表单验证规则
const auditRules = reactive({
    auditor: [{ required: true, message: '请选择审核人', trigger: 'change' }],
    comment: [{ required: true, message: '请输入审批意见', trigger: 'blur' }],
    checkRes: [{ required: true, message: '请选择审核结果', trigger: 'change' }]
});

// 列配置
const tableColumns = ref([
  { prop: 'id', label: 'ID' },
  { prop: 'code', label: '编码' },
  { prop: 'date', label: '日期' },
  { prop: 'status', label: '状态' },
  { prop: 'skname', label: '仓管人' },
  { prop: 'delFlag', label: '删除状态' },
  { prop: 'createDate', label: '创建时间' },
  { prop: 'createUser', label: '创建人' },
  { prop: 'updateDate', label: '更新时间' },
  { prop: 'updateUser', label: '更新人' }
])

// 表格数据
const tableData = ref<CostAdjustment[]>([])
const fileInput = ref<HTMLInputElement | null>(null); // 文件输入框引用
const auditFormRef = ref();
const auditForm = reactive({
    code: '',
    auditor: '',
    comment: '',
    checkRes: null
});

const formatDate = (date: Date, isEndDate: boolean = false) => {
    const pad = (num: number) => num.toString().padStart(2, '0');
    const year = date.getFullYear();
    const month = pad(date.getMonth() + 1);
    const day = pad(date.getDate());
    
    // 如果是结束日期，时间设为 23:59:59
    if (isEndDate) {
        return `${year}-${month}-${day} 23:59:59`;
    }
    return `${year}-${month}-${day} 00:00:00`;
};

async function fetchData(page: number) {
  try {
    const params = new URLSearchParams()
    params.append('pageNow', page.toString())
    params.append('pageSize', pageSize.value.toString())

    if (queryConditions.code) {
      params.append('code', queryConditions.code)
    }
    if (queryConditions.status !== null) {
      params.append('status', queryConditions.status.toString())
    }
    if (queryConditions.dateRange.length === 2) {
      // 如果 v-model 拿到的是字符串，再 new Date() 一下
  const startRaw = queryConditions.dateRange[0]
  const endRaw   = queryConditions.dateRange[1]

  const startDateObj = typeof startRaw === 'string'
    ? new Date(startRaw)
    : startRaw
  const endDateObj   = typeof endRaw   === 'string'
    ? new Date(endRaw)
    : endRaw
  const start = formatDate(startDateObj, false)  // "yyyy-MM-dd 00:00:00"
  const end   = formatDate(endDateObj,   true)   // "yyyy-MM-dd 23:59:59"

console.log('start →', start)
console.log('end   →', end)
  // 真正传给后端
  params.append('startDate', start)
  params.append('endDate',   end)
    }


    
    const resp = await request.post(
      'kc/proChange/getPage',
      params,
      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
    )
    const d = resp.data.data
    tableData.value = d.list || []
    total.value = d.total || 0
    pageNo.value = d.pageNo || page
  } catch (error) {
    ElMessage.error('获取成本调整数据失败')
    console.error(error)
    tableData.value = []
    total.value = 0
  }
}

// 分页变化
function handlePageChange(newPage: number) {
  fetchData(newPage)
}

// 操作按钮
function handleTableAction(actionName: string,selectedRows?:any) {
  if (actionName === 'add') {
    router.push({ name: 'Addcbtz' })
  }
  if(actionName === 'downLoadTemplate'){
    handleDownloadTemplate()
  }
  if(actionName ==='export'){
    handleExport(selectedRows)
  }
  if(actionName ==='import'){
    fileInput.value?.click();
  }
}

// 重置条件
function reset() {
  queryConditions.code = ''
  queryConditions.status = null
  queryConditions.dateRange = []
  fetchData(1)
}

// 编辑 & 删除
const router = useRouter()
const editVisible = ref(false)
const editRow = ref<CostAdjustment | null>(null)

function openEditDialog(row: CostAdjustment) {
  router.push({ name: 'EditCBTZ', params: { code: row.code } })
}

async function handleDelete(row: CostAdjustment) {
  try {
    await ElMessageBox.confirm(
      '确定要删除该条记录吗？此操作不可恢复！',
      '警告',
      { type: 'warning' }
    )
    await request.post(
      'kc/proChange/del',
      new URLSearchParams({ code: row.code.toString() }),
      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
    )
    ElMessage.success('删除成功')
    fetchData(pageNo.value)
  } catch (err) {
    if (err === 'cancel') {
      ElMessage.info('已取消删除')
    } else {
      ElMessage.error('删除失败')
      console.error(err)
    }
  }
}

//导出方法
const handleExport = async (selectedRows?: any[]) => {
    // 过滤掉前端添加的额外字段
    const filteredRows = selectedRows ? selectedRows.map(row => {
        const {index, docDate,createTime ,updateTime, ...rest} = row;
        return rest;
    }) : [];
    console.log('过滤后的 filteredRows:', filteredRows);
    const params = {
        selectedRows: filteredRows || [] // 包含选中行
    };
    // const loading = ElLoading.service({text: "正在导出..."});
    try {
        const response = await request.post("kc/proChange/export", params, {
            responseType: "blob",
        });
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", "成本调整信息表.xlsx");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        ElMessage.success("导出成功");
    } catch (error) {
        console.error("导出失败:", error);
        ElMessage.error("导出失败，请稍后重试");
    } finally {
        // loading.close();
    }
};

//下载模板
const handleDownloadTemplate = async () => {
    try {
        const response = await request.get('kc/proChange/template', {
            responseType: 'blob',
        });
        console.log(response)
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', '成本调整表.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        ElMessage.success('模板下载成功');
    } catch (error) {
        ElMessage.error('模板下载失败，请稍后重试');
    }
}

//导入方法
const handleFileSelect = async (event: Event) => {
    const input = event.target as HTMLInputElement;
    const file = input.files?.[0];
    if (!file) {
        ElMessage.warning('未选择文件');
        return;
    }

    // 校验文件后缀
    const allowedExtensions = ['.xlsx', '.xls'];
    const fileExtension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
    if (!allowedExtensions.includes(fileExtension)) {
        ElMessage.error('文件格式不正确，仅支持 .xlsx 和 .xls 文件');
        input.value = ''; // 重置文件输入框
        return;
    }

    // 校验文件大小
    const maxFileSize = 10 * 1024 * 1024; //10MB
    if (file.size > maxFileSize) {
        ElMessage.error(`文件大小超过限制，最大允许10MB，当前文件大小'${file.size.toFixed(2)}MB'`);
        input.value = ''; //重置
        return;
    }

    const formData = new FormData();
    formData.append('file', file);

    // const loading = ElLoading.service({text: '正在导入...'});
    try {
        const response = await request.post('kc/proChange/import', formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
            },
        });
        console.log(response.data.msg, ",", response.data.code)
        if (response.data.code === '200') {
            ElMessage.success('导入成功');
            await fetchData(pageNo.value); // 刷新表格数据
        } else {
            ElMessage.error(response.data.msg || "导入失败！");
        }
    } catch (error) {
        ElMessage.error('导入失败，请稍后重试');
        console.log(error)
    } finally {
        // loading.close();
        input.value = ''; // 重置文件输入框
    }
};

// 审核方法
const handleRowAudit = (row: CostAdjustment) => {
    auditForm.code = row.code
    auditDialogVisible.value = true
    console.log('当前审核单据:', row.code)
}

const submitAudit = async () => {
    // 表单验证
    if (!await auditFormRef.value?.validate()) return;

    // const rawArray = toRaw(selectedDocs.value);
    // const docCodeValue = rawArray[0];


    try {
        const response = await request.post('kc/proChange/check', {
            code: auditForm.code,
            typeId: 7,
            status:  3,
            checkManId: auditForm.auditor,  // 绑定审核人ID
            checkComment: auditForm.comment, // 绑定审批意见
            checkRes: auditForm.checkRes // 绑定审核结果
        });
        ElMessage.success(response.data.message);
        console.log(auditForm.code)
        // let res = await request.post('kc/proChange/getOne',{
        //   code: auditForm.code
        // })
        // if(res.data.code==200&&res.data.data.status==3){
        //   res = await request.post('kc/proChange/changePrice',{
        //   costAdjustment: res.data.data   
        // })
        //  if(response.data.code==200){
          ElMessage.success('审核完成')
        //  }else{
        //   ElMessage.warning('审核拒绝');
        // }
        auditDialogVisible.value = false;
        fetchData(pageNo.value); // 刷新表格数据
    } catch (error) {
        ElMessage.error('审核提交失败');
    } finally {
        // 重置表单
        auditForm.auditor = '';
        auditForm.comment = '';
    }
};

// 首次加载
fetchData(1)
</script>

<style scoped>
.mb-4 {
  margin-bottom: 16px;
}
</style>
